
#include "CMQTTClient.h"
#include "clip.h"
#include <Windows.h>
#include <iostream>
#include <string>
#include <codecvt>
#include "WideMultiChange.h"
#include <time.h>
#include <fstream>
#include <vector>
#include <map>
#include "Login.h"

using namespace std;
using namespace ItsUtils;

//#define ADDRESS "tcp://192.168.11.27:1883"
#define ADDRESS "tcp://116.85.22.108:1883"
#define TOPIC "clipboard/001"
#define CLIENTID "clipboard_cliper"
#define QOS         0
#define TIMEOUT     10000L

void delivered(void *context, MQTTClient_deliveryToken dt)
{
	printf("Message with token value %d delivery confirmed\n", dt);
}

int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
	int i;
	char* payloadptr;

	//printf("Message arrived\n");
	//printf("     topic: %s\n", topicName);
	//printf("   message: ");

	//payloadptr = (char*)message->payload;
	//for (i = 0; i<message->payloadlen; i++)
	//{
	//	putchar(*payloadptr++);
	//}
	//putchar('\n');

	int len = (int)message->payloadlen+1;
	char* data_tmp = (char*)malloc(len);
	memset(data_tmp, 0, len);
	//memcpy(data_tmp, (char*)message->payload, len);
	snprintf(data_tmp, len, "%s", message->payload);
	string data = data_tmp;
	int pos = data.find("_");
	if (0 != pos)
		data = data.substr(pos + 1);
	data = utf8ToMulti(data.c_str());
	//data = multiToUtf8(data.c_str());
	cout << data << endl;
	MQTTClient_freeMessage(&message);
	MQTTClient_free(topicName);
	delete data_tmp;
	return 1;
}

void connlost(void *context, char *cause)
{
	printf("\nConnection lost\n");
	printf("     cause: %s\n", cause);
}

enum {
	LOCAL_FILE_NOT_EXIST = -1,
	OPEN_LOCAL_FILE_FAILED = -2,
};

map<time_t, string> dataMap;

int getHistoryData(map<time_t, string>& dataMap)
{
	//获取当前时间
	time_t timeNow;
	time_t timeOld;
	time(&timeNow);

	string line;
	ifstream fin("history.data");
	if (!fin)
		return LOCAL_FILE_NOT_EXIST;
	int pos;
	string time_tmp;
	while (getline(fin, line))
	{
		pos = line.find("_");
		if (0 != pos)
		{
			time_tmp = line.substr(0, pos);
			line = line.substr(pos + 1);

			timeOld = atoi(time_tmp.c_str());
			if ((timeNow - timeOld) < (60 * 60 * 24))
			{
				dataMap.insert(pair<time_t, string>(timeOld, line));
			}
		}
	}
	fin.close();
	return 0;
}

int writeData(string data)
{
	ofstream outfile;
	outfile.open("history.data", ios::app);
	if (!outfile)
		return OPEN_LOCAL_FILE_FAILED;

	outfile << data << endl;
	outfile.close();
	return strlen(data.c_str());
}

int main() {

	CLogin clogin;
	loginInfo info;
	int data;
BEGIN:
	data = -1;
	while (data != 0 && data != 1)
	{
		cout << "Select sign up or login." <<endl;
		cout<<"Sign up: Input 0" << endl; cout << "Login: Input 1" << endl;
		cin >> data;
	}
	//注册
	if (data == 0)
	{
		cout << "Username: " << endl;
		cin >> info.username;
		cout << "Password: " << endl;
		cin >> info.password;
		int ret = clogin.signup(info);

		if (ret == 0)//失败
		{
			cout << "Sign up failed!" << endl;
			Sleep(1000);
			goto BEGIN;
			//exit(0);
		}
		else//注册成功，进入登录
		{	
			//cout << "Sign up successfully!" << endl;
			data = 1;
		}

	}
	//登录
	if (data == 1)
	{
		cout << "Username: " << endl;
		cin >> info.username;
		cout << "Password: " << endl;
		cin >> info.password;
		int ret = clogin.login(info);
		if (ret == -1)
		{
			cout << "Login failed!" << endl;
			Sleep(1000);
			goto BEGIN;
			//exit(0);
		}
	}

	cout << "Get history data from local file..." << endl;
	getHistoryData(dataMap);

	CMQTTClent sub_client;
	sub_client.conf.address = ADDRESS;
	sub_client.conf.clientID = CLIENTID;
	sub_client.conf.qos = QOS;
	//sub_client.conf.topic = TOPIC;
	sub_client.conf.topic = info.topic;
	sub_client.conf.timeout = TIMEOUT;
	sub_client.conf.type = SUBSCRIBE;
	sub_client.conf.keepAliveInterval = 20;
	sub_client.conf.cleanSession = 1;
	sub_client.conf.connlostCB = NULL;
	sub_client.conf.deliverycompleteCB = NULL;
	sub_client.conf.msgCB = &msgarrvd;
	sub_client.init();

	if (!dataMap.empty())
	{
		map<time_t, string>::iterator itr = dataMap.begin();
		for (; itr != dataMap.end(); ++itr)
			cout << itr->second << endl;
	}

	sub_client.startSub();

	getchar();
	//getchar();
}